/**
 * Description:条件变量的使用 
 * File: cond.c |Time: 2021-04-06 10:33
 */


#include <stdio.h>
#include <pthread.h>
#include <unistd.h>

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;

// 线程一任务
void * pfunc_1(void * param1)
{
    pthread_mutex_lock(&mutex);
    printf("线程1开始执行\n");
    sleep(1);
    pthread_cond_wait(&cond, &mutex);

    printf("线程1执行完成\n");
    pthread_mutex_unlock(&mutex);
    return NULL;
}

// 线程二任务
void * pfunc_2(void * param2)
{
    pthread_mutex_lock(&mutex);
    printf("线程2开始执行\n");
    sleep(1);
    pthread_cond_wait(&cond, &mutex);

    printf("线程2执行完成\n");
    pthread_mutex_unlock(&mutex);
    return NULL;
}

void * pfunc_week_up(void * cond)
{
    pthread_mutex_lock(&mutex);
    // printf("唤醒所有线程\n");
    // pthread_cond_broadcast(&cond);

    printf("唤醒一个线程\n");
    pthread_cond_signal(cond);

    pthread_mutex_unlock(&mutex);
    return NULL;
}

int main(int argc, char *argv[])
{
    printf("主程序开始运行\n");

    pthread_t pid1;
    pthread_t pid2;
    pthread_t pweek_up;

    pthread_create(&pid1, NULL, pfunc_1, NULL);
    pthread_create(&pid2, NULL, pfunc_2, NULL);
    pthread_create(&pweek_up, NULL, pfunc_week_up, &cond);


    pthread_join(pweek_up, NULL);
    pthread_join(pid1, NULL);
    pthread_join(pid2, NULL);

    printf("主程序运行结束\n");
    return 0;
}

